package com.wjn.basic.datastruct.linklist;

/**
 * 单向链表的实现
 */
public class LinkedList {
    public Node head;
    public Node current;

    //向链表中添加数据
    public void add(int n){
        if (head==null){
            head=new Node(n);
            current=head;
        }
        else {
            current.next=new Node(n);
            current=current.next;//移动指针到新添加的
        }
    }
    //打印链表
    public void print(Node node) {
        if (node == null) {
            return;
        }

        current = node;
        while (current != null) {
            System.out.println(current.data);
            current = current.next;
        }
    }


    //翻转链表
    public Node reviseNode(Node head) {
        if (head==null || head.next==null){
            return head;
        }
        Node current=head;
        Node reverseHead=null;//翻转后的头节点

        while(current!=null){
            Node temp=current.next;  //将当前节点的下一个节点暂存
            current.next=reverseHead;    //当前节点指向翻转后的头结点
            reverseHead=current;      //将要翻转的
            current=temp;
        }
        return reverseHead;
    }


    //获取链表的长度
    public int getLength(Node head) {
        if (head == null) {
            return 0;
        }

        int length = 0;
        Node current = head;
        while (current != null) {
            length++;
            current = current.next;
        }
        return length;
    }


    //Node节点
    class Node{
        int data;
        Node next;
        public Node(int data){
            this.data=data;
        }
    }


    public static void main(String[] args) {
        LinkedList linkedList=new LinkedList();
        for (int i=0;i<10;i++){
            linkedList.add(i);
        }
        linkedList.print(linkedList.head);

        //翻转链表
        Node node=linkedList.reviseNode(linkedList.head);
        System.out.println("翻转链表");
        linkedList.print(node);


    }


}
